app
.controller("AppCtrl",function($rootScope,$scope,$route,$location,$http,fileReader){
	//atomicNotifyService.info('Yes, this is the default notification :D');		
	$scope.dataURItoBlob = function (dataURI,filename) {
		filename = filename == null ? 'cropper-image' : filename;
		var arr = dataURI.split(','), mime = arr[0].match(/:(.*?);/)[1],
			bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
		while(n--){
			u8arr[n] = bstr.charCodeAt(n);
		}
		var blob = new Blob([u8arr], {type:mime});
		var file = new File([blob], filename + '.' +  blob.type.slice(blob.type.lastIndexOf('/')+1) , {type:mime});
		return file;
	}
	
	$scope.bytesToSize = bytesToSize;
	
	//返回一个函数，用于生成子scope的getFile
	//在子scope中生成两个属性，文件属性file，图片的16进制base64属性
	$scope._getFile = function(scope){
		return function (fn) {	//用来显示图片
			fileReader.readAsDataUrl(scope.file, scope)
			.then(function(result) {
				scope.base64 = result;
				if(fn){
					fn(result);
				}
			});
		};			
	}


	//代码块
	//用法：$scope.render = $scope.$parent._render($scope);
	$scope._render = function( scope , collection) {
		return function(fn){
			if ( typeof fn === 'function' ) {
				scope.data.sort( function(x,y){
					return fn(x,y);
				} );
			} else {
				$scope.db.count( collection, scope.query).success(function(res){
					var total = res.data
					if(scope.pageList !== undefined){
						scope.pageList.total = total;
						scope.pageList.list();
					}

					if ( total > 0 ){
						if(scope.pageList !== undefined){
							scope.changePage(scope.pageList.page);							
						}						
					} else {
						scope.data = [];
					}
				});
			}
		}
	}
	
	//代码块，在修改页面中，改变缩略图时实时显示修改的图片
	$scope.changeBase64 = function(img,base64){
		if ( base64 ) {
			//从src替换掉原来的图片
			var src = img.attr('src');
			if ( src ) {
				img.attr('src',base64 );
			}
			var ngSrc = img.attr('ng-src');
			//从ng-src替换掉原来的图片
			if ( ngSrc ) {
				img.attr('ng-src',base64 );
			}
		}
	}
	
	//用于设置子scope的文件属性，将子$scope.file与$scope.base64赋值给obj
	$scope.setFile = function(scope,obj){	
		if (scope.base64) {
			obj.base64 = scope.base64;
			if (scope.file) {
				
				obj.file = scope.file;
			}
		}
	}
	
	
	$scope.setImageFile = function(scope,obj){	
		if ( scope.selectedOriginal === true ) {	//添加原图
			if (scope.base64 && scope.file) {
				obj.file = scope.file;
			}
		} else if ( scope.selectedOriginal === false ) {	//添加缩略图
			var filename = null;
			if ( scope.file && scope.file.name ) {
				filename = scope.file.name.replace(/\.\w+$/,"");
				filename = '从[' + filename + ']裁剪';
			}
			obj.file = $scope.dataURItoBlob(scope.resImageDataURI,filename);
		}
	}
	
	//获取所有的控制器名
	function getControllers(app){
		//获取所有的控制器
		var controllers = app._invokeQueue.map(function(x){
			if (x[0]=="$controllerProvider") {
				return x[2][0];
			}
		} ).filter(function(x){
			return x!==undefined && x!=null;
		} );
		return controllers;
	}
	
	/*
		获取表格中选择的id，返回的是数组
	*/
	$scope.getCheckedIds = function (collection) {
		//为了兼容ng与浏览器，_id取名mgid
		var ids = angular.element("table[collection='" + collection + "'] tr").has("input:first:checked").map(function(){
			return angular.element(this).attr('mgid');
		}).get();
		return ids;
	}

	
	//切换路由
	$scope.changeRoute = function(url) {
		$location.path(url);		
		
		
		/*
		if ( url === undefined ){
			url = $location.path().replace(/^\/|\/$/,"").split("/").map(function(item){
				return item.charAt(0).toUpperCase() + item.slice(1).toLowerCase();
			} ).join("") + 'Ctrl';
		}
		*/
	};
  
	//生成db属性，用于子$scope
	$scope.db = new Db(APP_PATH,$http);
	
	$scope.execute = function ( res ) {
		if ( res.status== 1) {
			
			swal(
				{   
					title: (res && res.info) ? res.info : "操作成功",   
					text: (res && res.data) ? res.data : "按“确定”按钮返回",   
					type: "success",   
					confirmButtonColor: "#DD6B55",   
					confirmButtonText: "确定",   
					closeOnConfirm: true
				}
			);
		} else {
			swal(
				{
					title: (res && res.info) ? res.info : "操作失败", 
					text: (res && res.data) ? res.data : "按“确定”按钮返回",  
					type: "error",
					confirmButtonColor: "#DD6B55",
					confirmButtonText: "确定",
					closeOnConfirm: true
				}
			);				
		}		
	}
	
	$scope.success = function(res) {
		swal(
			{   
				title: "操作成功",   
				text: (res && res.info) ? res.info : "按“确定”按钮返回",   
				type: "success",   
				confirmButtonColor: "#DD6B55",   
				confirmButtonText: "确定",   
				closeOnConfirm: true
			}
		);
	};
	$scope.error = function(res) {
		swal(
			{
				title: "操作失败",
				text: (res && res.info) ? res.info : "按“确定”按钮返回",  
				type: "error",
				confirmButtonColor: "#DD6B55",
				confirmButtonText: "确定",
				closeOnConfirm: true
			}
		);		
	}
	
	$scope.loadCropperImage = function() {
		$('#inputImage').trigger('click');
	}	
	
	$scope.getCropperData = function() {
		console.log($('#inputImage').cropper('getData'));
	}
	
})
.controller("AboutusEditCtrl",function($scope,$timeout){
		$scope.db.findOne("about").success(function(res){
			$scope.post = res.data;
			$timeout(function(){
				UE.getEditor('editorContainer').setHeight(500);
				UE.getEditor('editorContainer').setContent($scope.post.content);
			} ,300 );		
		});
	
	$scope.submit = function(){	
		$scope.post.content = UE.getEditor('editorContainer').getContent();
		$scope.db.update( 'about', $scope.post).success( function(res){
			$scope.execute(res);
		} ) ;
	};	
})
.controller("ContactEditCtrl",function($scope,$timeout){
	$scope.db.find("contact").success(function(res){
		if (res.data) {
			$scope.contact = res.data;	
		} else {
			$scope.contact = [];	
		}
		
	});
	
	$scope.addLine = function() {
		if ( !$scope.contact.length || $scope.contact[$scope.contact.length-1].meta ) {
			$scope.contact[$scope.contact.length] = {};
		} else {
			$scope.error({info:'添加完上一行，才能添加新行'});
		}	
	}
	
	//删除一行
	$scope.delLine = function(row,index) {
		if ( !row.id ) {
			$scope.contact.splice(index,1);
			return;
		}
		swal(
			{   
				title: "<span style='font-size:80%;'>你确定要该行吗?</span>",   
				text: "删除之后将无法恢复！",   
				type: "warning",
				html: true,
				showCancelButton: true, 
				cancelButtonText: '取消',
				confirmButtonColor: "#DD6B55",   
				confirmButtonText: "删除",   
				closeOnConfirm: false,
				showLoaderOnConfirm: true
			}, 
			function() {  
				$scope.db.removeById("contact", row.id ).success(function(res,status){
					for( var i in $scope.contact ) {
						if ( $scope.contact[i].id == row.id ) {
							$scope.contact.splice(i,1);
							break;
						}
					}
					swal({   
						title: "成功删除!",   
						text: "提示消息框1秒后自动关闭.",   
						timer: 1000,   
						showConfirmButton: false });					
				} ) ;	
			});
	}
	
	$scope.submit = function() {
		$scope.db.url = APP_PATH + '?c=Contact&a=newContact';
		$scope.db.httpPost('',$scope.contact).success( function(res){
			if ( res.status == 1 ) {
				$scope.success(res);
				$scope.contact = res.data;
			} else {
				$scope.error(res);
			}
		} );
	}
})
.controller("CacheClearCtrl",function($scope,$timeout){
	$scope.appPath = "./home";
	$scope.clear = function(){
		$scope.db.url = APP_PATH + '?c=Index&a=clearCache';
		$scope.db.httpPost('',arguments).success( function(res){
			console.log(res)
			$scope.execute(res);
		} );		
	}
})
.controller("ConfigEditCtrl",function($scope,$timeout){
	$scope.config = {
		'site_name': '网站名称',
		'company_name' : '公司名称',
		'site_keywords' : '网站关键词',
		'site_description' : '网站描述'
	}

	$scope.db.url = APP_PATH + '?c=Index&a=getConfig';
	$scope.db.httpGet('',$scope.config).success( function(res){
		$scope.config = res.data;
	} );	
	
	$scope.submit = function(){	
		$scope.db.url = APP_PATH + '?c=Index&a=setConfig';
		$scope.db.httpPost('',$scope.config).success( function(res){
			$scope.execute(res);
		} );	
	};	
})
.controller("MailEditCtrl",function($scope,$timeout){
	$scope.config = {
		'MAIL_HOST': 'SMTP服务器',
		'MAIL_PORT' : '邮件发送端口',
		'MAIL_USERNAME' : '邮箱地址',
		'MAIL_PASSWORD' : '邮箱密码',
		'MAIL_FROMNAME' : '发件人姓名'
	}

	$scope.db.url = APP_PATH + '?c=Index&a=getConfig';
	$scope.db.httpGet('',$scope.config).success( function(res){
		$scope.config = res.data;
	} );	
	
	$scope.submit = function(){	
		$scope.db.url = APP_PATH + '?c=Index&a=setConfig';
		$scope.db.httpPost('',$scope.config).success( function(res){
			$scope.execute(res);
		} );	
	};	
})
.controller("MailTipCtrl",function($scope,$timeout){
	$scope.config = {
		'MAIL_TIP': '用户反馈提示'
	}

	$scope.db.url = APP_PATH + '?c=Index&a=getConfig';
	$scope.db.httpGet('',$scope.config).success( function(res){
		$scope.config = res.data;
	} );	
	
	$scope.submit = function(){	
		$scope.db.url = APP_PATH + '?c=Index&a=setConfig';
		$scope.db.httpPost('',$scope.config).success( function(res){
			$scope.success();
		} );	
	};	
})
.controller("NavCtrl",function($scope,$rootScope,$timeout,$location){
	$scope.logout = function() {
		swal(
			{   
				title: _USER.username+ " <small>您确定要注销吗？</small>",   
				text: "轻轻的您走了，正如您轻轻的来……",  
				html: true,
				showCancelButton: true, 
				cancelButtonText: '取消',
				confirmButtonColor: "#DD6B55",   
				confirmButtonText: "确定",   
				closeOnConfirm: true,
				showLoaderOnConfirm: true
			}, 
			function() {  
				//console.log( APP_PATH + "?c=Index&a=Logout&_rand=" + Math.random() )
				location.href = APP_PATH + "?c=Login&a=logout&_rand=" + Math.random()
			});		
	}
	$scope.submit = function(){
		$rootScope.postSearch = $scope.navSearch;
		$location.path('/post').replace();
	}
} )
.controller("LinkCtrl",function($rootScope,$scope){
	var currentPage = $scope.$parent.linkCurrentPage ? $scope.$parent.linkCurrentPage : 1;
	
	$scope.editModal = "linkEditModal";
	
	$scope.query = {};
	
	$scope.sort = {link_id:'ASC'};
	
	$scope.db.count( 'link', $scope.query).success(function(total){
		/*
		toal: 数据总条数
		perpage: 每页几条
		navLimit: 显示几个分页数字
		page: 当前页
		*/
		$scope.pageList = new PageList( total, 10 , 5,currentPage );
		$scope.pageList.list();
		$scope.changePage(currentPage);
	});
	
	/*因为页码用到了ngRepeat，在指令中使用不成功，必须使用函数 */
	$scope.changePage = function(page){
		if ( page>=1 && page<=$scope.pageList.count) {
			$scope.$parent.linkCurrentPage = page;
			$scope.pageList.page = page;
			$scope.pageList.prepare();
			$scope.db.find("link" ,{ where:$scope.query,order:$scope.sort,limit:$scope.pageList.skip + ',' +$scope.pageList.perpage}).success(function(data){
				data.forEach( function(item){
					item.is_display = parseInt(item.is_display);
				} )
				$scope.data = data;
				$scope.pageList.list();					
			}); 	
		}	
	};
	
	$scope.render = $scope.$parent._render($scope,'link');
	
	$scope.removeChecked = function() {		
		var ids = $scope.getCheckedIds('link');
		if ( ids.length>0 ) {
		swal(
			{   
				title: "<span style='font-size:80%;'>你确定要将这" + ids.length + "篇文章永久删除吗?</span>",   
				text: "文章永久删除后，将无法恢复！",   
				type: "warning",
				html: true,
				showCancelButton: true, 
				cancelButtonText: '取消',
				confirmButtonColor: "#DD6B55",   
				confirmButtonText: "永久删除",   
				closeOnConfirm: false,
				showLoaderOnConfirm: true
			}, 
			function() { 
				$scope.db.removeById("link", ids , function(){	
					$scope.render();
					swal({   
						title: "文章成功删除!",   
						text: "提示消息框2秒后自动关闭.",   
						timer: 2000,   
						showConfirmButton: false });					
				} );	
			});					
		}
	};

	$scope.update = function(data){
		$scope.db.update('link',data);
	};

})
.controller("LinkAddCtrl",function($scope){
	$scope.link = {};
	
	$scope.reset = function(){
		$scope.link = {};
	};

	//添加数据时的操作
	$scope.submit = function(){
		$scope.db.save('link',$scope.link);
	};
})
.controller('SystemCtrl',function($scope){
	$scope.db.httpGet('/system').success(function(res){
		$scope.data = res.data;
	});
})
.controller("CategoryCtrl",function($scope,$rootScope){
	$scope.render = function() {
		$scope.db.find( 'category',{order:{cat_order:'ASC',cat_id:'ASC'}}).success( function(res,status){
			$scope.cates = angular.copy(res.data);
			$scope.data = catTree(res.data);
		} );		
	}
	
	$scope.render();
	
	$scope.edit = function(cate) {
		$rootScope.tempCate = cate;
		$scope.changeRoute('/category/edit');
	}
	
	$scope.update = function(cate){
		$scope.setImageFile($scope,cate);
		delete cate.cover_path;
		$scope.db.update( 'category', cate);
	};
	
	$scope.remove = function ( cate ) {
		var cat_id = cate.cat_id;
		var ids = catTree(angular.copy($scope.cates),cat_id).map( function( item ){
			return item.cat_id;
		} );
		
		if ( ids.length>0 ) {	//含有子分类不能被删除
			swal( {
				title: "操作失败",
				text: "含有子分类的栏目不能删除，请先删除所有子分类！",
				type: 'error',
				showConfirmButton: true,
				confirmButtonText: "确定",
				confirmButtonColor: "#DD6B55"
			} );
		} else {
			$scope.db.count('post',{'cat_id':cat_id,'is_delete':0}).success(function(res) {	//取出该栏目下正常显示的文章个数
				count = parseInt(res.data);
				if ( count > 0) {	//如果有正常显示的文章，不能删除
					swal( {
						title: "操作失败",
						text: "该栏目下尚有" + count + "篇正常显示的文章，故不能被删除。<br />若要删除栏目，请先删除该栏目下的所有文章！",
						type: 'error',
						html: true,
						showConfirmButton: true,
						confirmButtonText: "确定",
						confirmButtonColor: "#DD6B55"
					} );					
				} else {					
					$scope.db.count('post',{'cat_id':['in',ids],is_delete:true}).success(function(res) {		//取出回收站里的文章个数
						count = parseInt(res.data);
						if ( count>0 ){
							swal(
								{   
									title: "你确定要删除该栏目吗?",   
									text: "在该栏目的回收站里的"+count+"篇文章也会被删除！",   
									type: "warning",   
									showCancelButton: true,
									cancelButtonText: '取消',
									confirmButtonColor: "#DD6B55",   
									confirmButtonText: "删除",   
									closeOnConfirm: false,
									showLoaderOnConfirm: true
								}, 
								function() {									
									$scope.db.removeById('category',cat_id).success(function(){
										$scope.db.remove('post',{'cat_id':cat_id},function(){	
											swal({   
												title: "从数据库中成功删除!",   
												text: "2 秒后自动关闭", 
												type: 'success',
												timer: 2000,   
												showConfirmButton: false 
											});
											$scope.render();
										} );
									});
															
								}
							);								
							
						} else {
							swal(
								{   
									title: "你确定要删除该栏目吗?",   
									text: "删除之后，将无法恢复！",   
									type: "warning",   
									showCancelButton: true,
									cancelButtonText: '取消',
									confirmButtonColor: "#DD6B55",   
									confirmButtonText: "删除",   
									closeOnConfirm: false,
									showLoaderOnConfirm: true
								}, 
								function() {  
									$scope.db.removeById('category',cat_id).success(function(){
										$scope.render();
										swal({   
											title: "从数据库中成功删除!",   
											text: "2 秒后自动关闭", 
											type: 'success',
											timer: 2000,   
											showConfirmButton: false 
										});
									});				
								}
							);	
						}
					});					
				}
			});			
		}
	}

})
.controller("CategoryAddCtrl",function($http,$scope){	//添加数据时的操作
	$scope.cate = {};
	$scope.cate.parent_id = '0';
	
	$scope.getFile = $scope.$parent._getFile($scope);
	
	//取得分类列表数据
	$scope.db.find( 'category',{}).success( function(res,status){
		$scope.data = catTree(res.data);		
		
	});


	$scope.submit = function(){
		$scope.setImageFile($scope,$scope.cate);
		delete $scope.cate.cover_path;
		$scope.db.save("category",$scope.cate).success( function(res,status){
			if(res.status==1){
				$scope.success(res);
				$scope.db.find( 'category',{}).success( function(res,status){
					$scope.data = catTree(res.data);					
				} );			
			} else {
				$scope.error(res);				
			}			
		} );
		/*
		$scope.db.httpMultipart( '/save/category', 'POST', $scope.cate).success( function(res,status){
			$scope.success(res,status);
			$scope.db.find( 'category',{}).success(function(data){
				$scope.data = catTree(data);
			}) ;
		} ).error(function(res,status){
			$scope.error(res,status);
		} );
		*/
	};
})
.controller("CategoryEditCtrl",function($scope,$rootScope){
	//如果将修改页面刷新，将会出错TypeError: Cannot read property '_id' of undefined

	if ($rootScope.tempCate===undefined){
		$scope.changeRoute("/category");
	}
	
	$scope.db.findById("category",$rootScope.tempCate.cat_id).success( function(res){
		$scope.cate = res.data;
		$scope.cate.cat_order = parseInt($scope.cate.cat_order);
		$scope.showInputFile = res.data.cover_path ? false : true;			
	} );
	
	$scope.changeCover = function(){
		$scope.showInputFile=!$scope.showInputFile;
		$('#fileInput').trigger('click');
	}

	
	$scope.getFile = $scope.$parent._getFile($scope);

	$scope.db.find( 'category',{}).success( function(res){
		$scope.data = catTree(angular.copy(res.data) );
		$scope.selfTree = catTree(res.data,$rootScope.tempCate.cat_id);
		$scope.selfTree.unshift($rootScope.tempCate);
		$scope.selfTree = $scope.selfTree.map( function(item){
			return item.cat_id;
		} );	
	} );
	
	$scope.submit = function(){
		$scope.setImageFile($scope,$scope.cate);
		delete $scope.cate.cover_path;
		$scope.db.httpMultipart( '/update/category', 'POST', $scope.cate).success( function(res,status){
			
			$scope.success(res,status);
		} ).error(function(res,status){
			$scope.error(res,status);
		} );
	};
})
.controller("ImageAddCtrl" , function($scope){

	$scope.image = {};
	
	$scope.db.find( 'album',{},function(data){
		$scope.data = catTree(data)
	} );	
} )
.controller('ImageCutCtrl',function($scope){

	
} )
.controller("ImageCropCtrl" ,function($scope){
	$scope.$parent.selectedOriginal = null;
	$scope.imageDataURI='';
	
	$scope.resImgSize=200;	//裁减图尺寸
	$scope.selMinSize=200;	//选区最小尺寸，这两个保持一致比较合理
	
	$scope.size='big';
	$scope.type='square';
	$scope.changeOnFly = false;        
	$scope.resImageDataURI='';
	$scope.resImgFormat='image/png';
	$scope.resImgQuality=1;
	
	
	$scope.hidePanel = true;
	
	
	$scope.aspectRatio=0.5;
	$scope.onChange=function($dataURI) {
		if ( $scope.$parent.selectedOriginal !== null ) {
			$scope.$parent.selectedOriginal = false;	
		} else if ( $scope.hidePanel ) {
			$scope.hidePanel = false;
		}
		
	  console.log('onChange fired');
	};
	$scope.onLoadBegin=function() {
	  console.log('onLoadBegin fired');
	};
	$scope.onLoadDone=function() {
		$scope.$parent.selectedOriginal = true;
	  console.log('onLoadDone fired');
	};
	$scope.onLoadError=function() {
	  console.log('onLoadError fired');
	};
	
	var handleFileSelect=function(evt) {
	  
	  $scope.enableCrop = true;
	  var file=evt.currentTarget.files[0];
	  var reader = new FileReader();
	  
	  reader.onload = function (evt) {
		$scope.$apply(function($scope){
		  $scope.imageDataURI=evt.target.result;
		});
	  };
	  reader.readAsDataURL(file);
	};
	var fileInput = document.querySelector('#fileInput') ;
	angular.element( fileInput ).on('change',handleFileSelect);
	$scope.$watch('resImageDataURI',function(){
		$scope.$parent.resImageDataURI = $scope.resImageDataURI;
	});	
} )
.controller("PostCtrl",function($scope,$rootScope,$timeout){	
	var currentPage = $scope.$parent.postCurrentPage ? $scope.$parent.postCurrentPage : 1;
	
	$scope.modal = "postModal";
	
	$scope.query = {};
	
	if ( _USER.username!='admin' ) {
		$scope.query.user_id = _USER.id;
	}
	
	$scope.edit = function(post){
		$rootScope.tempPost = post;
		$scope.changeRoute("/post/edit");
	};
	
	$scope.sort = {'is_top':'DESC','post_id':'DESC'};
	
	
	$scope.db.find( 'category',{order:{cat_order:'ASC',cat_id:'ASC'}}).success(function(res){
		$scope.cates = catTree(res.data);
	});
	
	$scope.selectCate = function(cat_id) {
		if ( cat_id ) {
			var ids = catTree($scope.cates,cat_id).map( function( item ){
				return item.cat_id;
			} );
			ids.unshift(cat_id);
			$scope.query['cat_id'] = ['in',ids];			
		} else {
			delete $scope.query['cat_id'];
		}
		
		$scope.render();
	}
	
	$timeout( function(){
		$scope.db.count( 'post', $scope.query).success( function(res){		
			/*
			toal: 数据总条数
			perpage: 每页几条
			navLimit: 显示几个分页数字
			page: 当前页
			*/
			$scope.pageList = new PageList( res.data, 10 , 5,currentPage );
			$scope.pageList.list();
			$scope.changePage(currentPage);
		});			
	} , 10); 

	
	/*因为页码用到了ngRepeat，在指令中使用不成功，必须使用函数 */
	$scope.changePage = function(page){
		if ( page>=1 && page<=$scope.pageList.count) {
			$scope.$parent.postCurrentPage = page;
			$scope.pageList.page = page;
			$scope.pageList.prepare();
			$scope.db.find("post" ,{ where:$scope.query, field:'post_id as _id,title,cover_path,is_display,is_top,cat_id,is_audit,add_time' ,order:$scope.sort,page:$scope.pageList.page+','+$scope.pageList.perpage}).success( function(res,status){
				$scope.data = res.data;
				$scope.pageList.list();					
			} );		
		}	
	};
	
	$scope.render = $scope.$parent._render($scope,'post');
	


})
.controller("PostIndexCtrl", function($scope,$rootScope,$timeout){
	if( $scope.$parent.query ){
		$scope.$parent.query.is_delete = 0;
		
		$rootScope.$watch("postSearch", function (val) {
			if ( $rootScope.postSearch ) {
				$scope.$parent.query.content = ['like','%' + $rootScope.postSearch + '%'] ;		
			} else if ( $scope.$parent.query ) {
				delete $scope.$parent.query.content;
			}	
			$scope.render();
		});		
		
	}	
	
	
	//转移分类
	$scope.transferCategory = function(cat_id) {
		if ( cat_id ){
			var ids = $scope.getCheckedIds('post');
			var cate = null;
			for ( var i in $scope.cates) {
				if ( $scope.cates[i].cat_id == cat_id ) {
					cate = $scope.cates[i];
				}
			}
			var index = null;
			
			//将该分类下的文章ID从数组中删除
			$scope.data.forEach( function( item ){
				if ( item.cat_id == cat_id ) {
					index = ids.indexOf(item._id);
					if ( index != -1 ) {
						delete ids[index];
					}
				}				
			} )
			ids = ids.filter( function(x){return x!=null;} );
			if ( ids.length>0 ) {
				$timeout( function(){
					swal(
						{   
							title: "<span style='font-size:80%;'>你确定要转移所选 文章到指定栏目“"+ cate.cat_name +"”中吗?</span>",   
							text: "所选文章中共有" + ids.length + "篇文章需要转移！",   
							type: "info",
							html: true,
							showCancelButton: true, 
							cancelButtonText: '取消',
							confirmButtonColor: "#DD6B55",   
							confirmButtonText: "确定",   
							closeOnConfirm: false,
							showLoaderOnConfirm: true
						}, 
						function() { 
							$scope.db.modifyByIds("post",ids,{'cat_id':cat_id}).success( function(res,status){
								$scope.render();
								swal({   
									title: "文章成功转移分类!",   
									text: "提示消息框2秒后自动关闭.",   
									timer: 2000,   
									showConfirmButton: false });							
							} );
						}
					);	
					
				} );

			} else {
				swal(
					{   
						title: "所选文章全部都是栏目“"+cate.cat_name+"”中的文章！",   
						text: "按“确定”按钮返回",   
						type: "success",   
						confirmButtonColor: "#DD6B55",   
						confirmButtonText: "确定",   
						closeOnConfirm: true
					});				
			}			
		}
		$scope.transfer_cat = '';
	}	
	
	//加入回收站
	$scope.recycle = function( _id ) {
		swal(
			{   
				title: "<span style='font-size:80%;'>你确定要将这篇文章移入回收站吗?</span>",   
				text: "文章移入回收站后，将不会在前端显示！",   
				type: "warning",
				html: true,
				showCancelButton: true, 
				cancelButtonText: '取消',
				confirmButtonColor: "#DD6B55",   
				confirmButtonText: "删除",   
				closeOnConfirm: false,
				showLoaderOnConfirm: true
			}, 
			function() {  
				$scope.db.modifyById("post",{is_delete:1},_id ).success(function(res,status){
					$scope.render();
					if ( res.status = 1 ){
						swal({   
						title: "文章成功移入回收站!",   
						text: "提示消息框2秒后自动关闭.",   
						timer: 2000,   
						showConfirmButton: false });						
					} else{
						$scope.error(res)
					}
										
				} ) ;	
			});
	}
	
	//将多篇选择的文章加入回收站
	$scope.recycleChecked = function() {
		var ids = $scope.getCheckedIds('post');
		if ( ids.length>0 ) {
		swal(
				{   
					title: "<span style='font-size:80%;'>你确定要将这" + ids.length + "篇文章移入回收站吗?</span>",   
					text: "文章移入回收站后，将不会在前端显示！",   
					type: "warning",
					html: true,
					showCancelButton: true, 
					cancelButtonText: '取消',
					confirmButtonColor: "#DD6B55",   
					confirmButtonText: "删除",   
					closeOnConfirm: false,
					showLoaderOnConfirm: true
				}, 
				function() { 
					$scope.db.modifyByIds("post", ids , {is_delete:1}).success(function(res,status){
						$scope.render();
						swal({   
							title: "文章成功移入回收站!",   
							text: "提示消息框2秒后自动关闭.",   
							timer: 2000,   
							showConfirmButton: false });						
					} ); 
				}
			);					
		}
	};
	
	//取消置顶
	$scope.removeStar = function() {
		var ids = $scope.getCheckedIds('post');
		if ( ids.length>0 ) {
			swal(
				{   
					title: "<span style='font-size:80%;'>你确定要取消这" + ids.length + "篇文章的置顶吗?</span>",   
					text: "取消置顶后，将不会在最上面显示！",   
					type: "warning",
					html: true,
					showCancelButton: true, 
					cancelButtonText: '取消',
					confirmButtonColor: "#DD6B55",   
					confirmButtonText: "确定",   
					closeOnConfirm: false,
					showLoaderOnConfirm: true
				}, 
				function() { 
					$scope.db.modifyByIds("post", ids , {is_top:0}).success( function(res,status){
						$scope.render();
						swal({   
							title: "文章成功取消置顶!",   
							text: "提示消息框2秒后自动关闭.",   
							timer: 2000,   
							showConfirmButton: false });						
					} );
				}
			);					
		}
	};	
	
} )
.controller("PostRecycleCtrl",function($scope){
	if( $scope.$parent.query ){
		$scope.$parent.query.is_delete = 1;
	}	
	

	$scope.restore = function( _id ) {
		$scope.db.switchBool("post",_id,'is_delete').success(function(){
			$scope.render();			
		});
	}
	
	
	$scope.removeChecked = function() {		
		var ids = $scope.getCheckedIds('post');
		if ( ids.length>0 ) {
		swal(
			{   
				title: "<span style='font-size:80%;'>你确定要将这" + ids.length + "篇文章永久删除吗?</span>",   
				text: "文章永久删除后，将无法恢复！",   
				type: "warning",
				html: true,
				showCancelButton: true, 
				cancelButtonText: '取消',
				confirmButtonColor: "#DD6B55",   
				confirmButtonText: "永久删除",   
				closeOnConfirm: false,
				showLoaderOnConfirm: true
			}, 
			function() { 
				$scope.db.removeById("post", ids).success(function(){	
					$scope.render();
					swal({   
						title: "文章成功删除!",   
						text: "提示消息框2秒后自动关闭.",   
						timer: 2000,   
						showConfirmButton: false });					
				});;	
			});					
		}
	};
	
	$scope.restoreChecked = function() {
		var ids = $scope.getCheckedIds('post');
		if ( ids.length>0 ) {
		swal(
			{   
				title: "<span style='font-size:80%;'>你确定要恢复这" + ids.length + "篇文章吗?</span>",   
				text: "文章恢复后，从回收站移入文章管理！",   
				type: "warning",
				html: true,
				showCancelButton: true, 
				cancelButtonText: '取消',
				confirmButtonColor: "#DD6B55",   
				confirmButtonText: "恢复",   
				closeOnConfirm: false,
				showLoaderOnConfirm: true
			}, 
			function() { 
				$scope.db.modifyByIds("post", ids , {is_delete:0}).success( function(res,status){
					$scope.render();
					swal({   
						title: "文章成功恢复!",   
						text: "提示消息框2秒后自动关闭.",   
						timer: 2000,   
						showConfirmButton: false });						
				} ); 
			});					
		}
	};

})
.controller("PostAddCtrl",function($http,$scope,$rootScope){	//添加数据时的操作

	$scope.db.find( 'category',{}).success(function(res){
		$scope.data = catTree(res.data)
	});

	$scope.submit = function(){
		var blob = $scope.dataURItoBlob($('#cropperImage').cropper('getCroppedCanvas').toDataURL('image/jpeg', 0.3));
		$scope.post.uploadImage = blob;
		$scope.post.user_id = _USER.id;

		$scope.post.content = UE.getEditor('editorContainer').getContent();
		$scope.db.save( 'post',  $scope.post).success( function(res,status){
			$scope.execute(res);
		} ) ;
	};

})
.controller("PostEditCtrl",function($scope,$rootScope,$timeout){
	//如果将修改页面刷新，将会出错TypeError: Cannot read property '_id' of undefined
	if ($rootScope.tempPost===undefined){
		$scope.changeRoute("/post");
	}
	
	$scope.hidePanel = true;
	

	$scope.db.find( 'category',{}).success(function(res){
		$scope.data = catTree(res.data);

		$scope.db.findById("post",$rootScope.tempPost._id).success(function(res){
			$scope.post = res.data;
			$scope.hidePanel = $scope.post.cover_path ? true : false;
			$timeout(function(){
				$("#viewMode0").trigger("click")
				UE.getEditor('editorContainer').setContent($scope.post.content);
			} ,200 );		
		});		
	});
	
	$scope.submit = function(){	
		delete $scope.post.cover_path;
		if ( !$scope.hidePanel ) {
			var blob = $scope.dataURItoBlob($('#cropperImage').cropper('getCroppedCanvas').toDataURL('image/jpeg', 0.3));
			$scope.post.uploadImage = blob;						
		} 

	
		$scope.post.content = UE.getEditor('editorContainer').getContent();
		$scope.db.update( 'post', $scope.post).success( function(res){
			$scope.execute(res)			
		} ) ;
	};	
})
.controller("SwiperCtrl",function($scope,$rootScope,$timeout){	
	var currentPage = $scope.$parent.swiperCurrentPage ? $scope.$parent.swiperCurrentPage : 1;
	
	$scope.query = {};
	
	if ( _USER.username!='admin' ) {
		$scope.query.user_id = _USER.id;
	}
	
	$scope.edit = function(swiper){
		$rootScope.tempSwiper = swiper;
		$scope.changeRoute("/swiper/edit");
	};
	
	$scope.sort = {'is_top':'DESC','id':'DESC'};
	
	$timeout( function(){	
		$scope.db.count( 'swiper', $scope.query).success( function(res){		
			/*
			toal: 数据总条数
			perpage: 每页几条
			navLimit: 显示几个分页数字
			page: 当前页
			*/
			$scope.pageList = new PageList( res.data, 10 , 5,currentPage );
			$scope.pageList.list();
			$scope.changePage(currentPage);
		});
	},10)
	
	/*因为页码用到了ngRepeat，在指令中使用不成功，必须使用函数 */
	$scope.changePage = function(page){
		if ( page>=1 && page<=$scope.pageList.count) {
			$scope.$parent.swiperCurrentPage = page;
			$scope.pageList.page = page;
			$scope.pageList.prepare();
			$scope.db.find("swiper" ,{ where:$scope.query, field:'id as _id,post_id,swiper_title,banner_path,is_display,is_top,add_time' ,order:$scope.sort,page:$scope.pageList.page+','+$scope.pageList.perpage}).success( function(res,status){
				$scope.data = res.data;
				$scope.pageList.list();					
			} );		
		}	
	};
	
	$scope.render = $scope.$parent._render($scope,'swiper');
	



})
.controller("SwiperIndexCtrl", function($scope,$rootScope,$timeout){
	if( $scope.$parent.query ){
		$scope.$parent.query.is_delete = 0;		
	}	
	
	//加入回收站
	$scope.recycle = function( _id ) {
		swal(
			{   
				title: "<span style='font-size:80%;'>你确定要将这篇文章移入回收站吗?</span>",   
				text: "文章移入回收站后，将不会在前端显示！",   
				type: "warning",
				html: true,
				showCancelButton: true, 
				cancelButtonText: '取消',
				confirmButtonColor: "#DD6B55",   
				confirmButtonText: "删除",   
				closeOnConfirm: false,
				showLoaderOnConfirm: true
			}, 
			function() {  
				$scope.db.modifyById("swiper",{is_delete:1},_id ).success(function(res,status){
					$scope.render();
					swal({   
						title: "文章成功移入回收站!",   
						text: "提示消息框2秒后自动关闭.",   
						timer: 2000,   
						showConfirmButton: false });					
				} ) ;	
			});
	}
	
	//将多篇选择的文章加入回收站
	$scope.recycleChecked = function() {
		var ids = $scope.getCheckedIds('swiper');
		if ( ids.length>0 ) {
		swal(
				{   
					title: "<span style='font-size:80%;'>你确定要将这" + ids.length + "个banner移入回收站吗?</span>",   
					text: "banner移入回收站后，将不会在前端显示！",   
					type: "warning",
					html: true,
					showCancelButton: true, 
					cancelButtonText: '取消',
					confirmButtonColor: "#DD6B55",   
					confirmButtonText: "删除",   
					closeOnConfirm: false,
					showLoaderOnConfirm: true
				}, 
				function() { 
					$scope.db.modifyByIds("swiper", ids , {is_delete:1}).success(function(res,status){
						$scope.render();
						swal({   
							title: "banner成功移入回收站!",   
							text: "提示消息框2秒后自动关闭.",   
							timer: 2000,   
							showConfirmButton: false });						
					} ); 
				}
			);					
		}
	};
	
	//取消置顶
	$scope.removeStar = function() {
		var ids = $scope.getCheckedIds('swiper');
		if ( ids.length>0 ) {
			swal(
				{   
					title: "<span style='font-size:80%;'>你确定要取消这" + ids.length + "个banner的置顶吗?</span>",   
					text: "取消置顶后，将不会在最上面显示！",   
					type: "warning",
					html: true,
					showCancelButton: true, 
					cancelButtonText: '取消',
					confirmButtonColor: "#DD6B55",   
					confirmButtonText: "确定",   
					closeOnConfirm: false,
					showLoaderOnConfirm: true
				}, 
				function() { 
					$scope.db.modifyByIds("swiper", ids , {is_top:0}).success( function(res,status){
						$scope.render();
						swal({   
							title: "banner成功取消置顶!",   
							text: "提示消息框2秒后自动关闭.",   
							timer: 2000,   
							showConfirmButton: false });						
					} );
				}
			);					
		}
	};	
	
} )
.controller("SwiperRecycleCtrl",function($scope){
	if( $scope.$parent.query ){
		$scope.$parent.query.is_delete = 1;
	}	
	

	$scope.restore = function( _id ) {
		$scope.db.switchBool("swiper",_id,'is_delete').success(function(){
			$scope.render();			
		});
	}
	
	
	$scope.removeChecked = function() {		
		var ids = $scope.getCheckedIds('swiper');
		if ( ids.length>0 ) {
		swal(
			{   
				title: "<span style='font-size:80%;'>你确定要将这" + ids.length + "个banner永久删除吗?</span>",   
				text: "文章永久删除后，将无法恢复！",   
				type: "warning",
				html: true,
				showCancelButton: true, 
				cancelButtonText: '取消',
				confirmButtonColor: "#DD6B55",   
				confirmButtonText: "永久删除",   
				closeOnConfirm: false,
				showLoaderOnConfirm: true
			}, 
			function() { 
				$scope.db.removeById("swiper", ids).success(function(){	
					$scope.render();
					swal({   
						title: "banner成功删除!",   
						text: "提示消息框2秒后自动关闭.",   
						timer: 2000,   
						showConfirmButton: false });					
				});;	
			});					
		}
	};
	
	$scope.restoreChecked = function() {
		var ids = $scope.getCheckedIds('swiper');
		if ( ids.length>0 ) {
		swal(
			{   
				title: "<span style='font-size:80%;'>你确定要恢复这" + ids.length + "个banner吗?</span>",   
				text: "banner恢复后，从回收站移入banner管理！",   
				type: "warning",
				html: true,
				showCancelButton: true, 
				cancelButtonText: '取消',
				confirmButtonColor: "#DD6B55",   
				confirmButtonText: "恢复",   
				closeOnConfirm: false,
				showLoaderOnConfirm: true
			}, 
			function() { 
				$scope.db.modifyByIds("swiper", ids , {is_delete:0}).success( function(res,status){
					$scope.render();
					swal({   
						title: "banner成功恢复!",   
						text: "提示消息框2秒后自动关闭.",   
						timer: 2000,   
						showConfirmButton: false });						
				} ); 
			});					
		}
	};

})
.controller("SwiperAddCtrl",function($http,$scope,$rootScope){	//添加数据时的操作
	$scope.getFile = $scope.$parent._getFile($scope);	
	$scope.swiper = {};
	$scope.submit = function(){
		$scope.swiper.user_id = _USER.id;		
		$scope.setFile($scope,$scope.swiper);
		
		if ( !$scope.swiper.base64 ) {
			$scope.error({info:"必须上传图片"});
		} else {
			delete $scope.swiper.base64;
			$scope.db.save( 'swiper', $scope.swiper).success( function(res){
				$scope.execute(res);
			} ) ;			
		}
	};

})
.controller("SwiperEditCtrl",function($scope,$rootScope,$timeout){
	//如果将修改页面刷新，将会出错TypeError: Cannot read property '_id' of undefined
	if ($rootScope.tempSwiper===undefined){
		$scope.changeRoute("/swiper");
	}
	
	$scope.swiper = $rootScope.tempSwiper;
	if ( $scope.swiper.post_id == 0 ) {
		delete $scope.swiper.post_id;
	}
	
	$scope.getFile = $scope.$parent._getFile($scope);	
	
	$scope.submit = function(){	
		$scope.swiper.id = $scope.swiper._id; 
		delete $scope.swiper.banner_path;
		delete $scope.swiper.base64;
		$scope.setFile($scope,$scope.swiper);		
		$scope.db.httpMultipart( '/update/swiper', 'POST',  $scope.swiper).success( function(){
			$scope.success();
		} ) ;
	};	
})

.controller("FeedbackCtrl",function($scope,$rootScope,$timeout){	
	var currentPage = $scope.$parent.feedCurrentPage ? $scope.$parent.feedCurrentPage : 1;
	
	$scope.modal = "feedModal";
	
	$scope.query = {is_display:'1'};
	
	$scope.reply = function(feed){
		$rootScope.tempFeed = feed;
		$scope.changeRoute("/feedback/reply");
	};
	
	$scope.sort = {'id':'DESC'};

	$timeout( function(){	
		$scope.db.count( 'feedback', $scope.query).success( function(res){		
			/*
			toal: 数据总条数
			perpage: 每页几条
			navLimit: 显示几个分页数字
			page: 当前页
			*/
			$scope.pageList = new PageList( res.data, 10 , 5,currentPage );
			$scope.pageList.list();
			$scope.changePage(currentPage);
		});
	} , 10);
	
	/*因为页码用到了ngRepeat，在指令中使用不成功，必须使用函数 */
	$scope.changePage = function(page){
		if ( page>=1 && page<=$scope.pageList.count) {
			$scope.$parent.feedCurrentPage = page;
			$scope.pageList.page = page;
			$scope.pageList.prepare();
			$scope.db.find("feedback" ,{ where:$scope.query, field:'id as _id,username,mail,tel,content,reply,subject,is_reply,is_display,feed_time,reply_time,ip,ip_area' ,order:$scope.sort,page:$scope.pageList.page+' , '+$scope.pageList.perpage}).success( function(res,status){
				$scope.data = res.data;
				$scope.pageList.list();					
			} );		
		}	
	};
	
	$scope.render = $scope.$parent._render($scope,'feedback');
	


})
.controller("FeedbackIndexCtrl", function($scope,$rootScope,$timeout){

	
	//加入回收站
	$scope.recycle = function( _id ) {
		swal(
			{   
				title: "<span style='font-size:80%;'>你确定要将这篇文章移入回收站吗?</span>",   
				text: "文章移入回收站后，将不会在前端显示！",   
				type: "warning",
				html: true,
				showCancelButton: true, 
				cancelButtonText: '取消',
				confirmButtonColor: "#DD6B55",   
				confirmButtonText: "删除",   
				closeOnConfirm: false,
				showLoaderOnConfirm: true
			}, 
			function() {  
				$scope.db.modifyById("post",{is_delete:1},_id ).success(function(res,status){
					$scope.render();
					swal({   
						title: "文章成功移入回收站!",   
						text: "提示消息框2秒后自动关闭.",   
						timer: 2000,   
						showConfirmButton: false });					
				} ) ;	
			});
	}	
	
} )
.controller("FeedbackReplyCtrl",function($scope,$rootScope,$timeout){
	//如果将修改页面刷新，将会出错TypeError: Cannot read property '_id' of undefined
	if ($rootScope.tempFeed===undefined){
		$scope.changeRoute("/feedback");
	}

	$scope.feed = $rootScope.tempFeed;	
	$scope.feed.reply_title = "回复 " + $scope.feed.subject;
	
	$scope.submit = function() {
		$scope.feed.reply = UE.getEditor('editorContainer').getContent();
		$scope.feed.id = $scope.feed._id;
	
		$scope.db.url = APP_PATH + '?c=Feedback&a=sendMail';
		$scope.db.httpPost('',$scope.feed).success( function(res){
			if ( res.status == 1 ) {
				$scope.success(res);
			} else {
				
					swal(
						{   
							title: "邮件发送失败",   
							text: res.info,   
							type: "error",  
							html : true,
							showCancelButton: true,
							cancelButtonText: '忽略',
							confirmButtonColor: "#DD6B55",   
							confirmButtonText: "删除该条留言",   
							closeOnConfirm: false,
							showLoaderOnConfirm: true
						}, 
						function() { 
								$scope.db.removeById('feedback',$scope.feed._id).success(function(){
									swal({   
										title: "从数据库中成功删除!",   
										text: "2 秒后自动关闭", 
										type: 'success',
										timer: 2000,   
										showConfirmButton: false 
									});
									$scope.changeRoute('/feedback');									
								});						
						});					
			}
		} );
	}
})

.controller( 'RoleAddCtrl' , function($scope){	
	$scope.role = {};
	$scope.role.pid = '0';	
	$scope.db.find( 'role',{order:{'id':'ASC'}}).success(function(data){
		$scope.data = catRole(data);
	});	
	
	
	$scope.submit = function() {
		$scope.db.url = APP_PATH + '/Rbac/addRoleHandler';
		$scope.db.httpPost('',$scope.role).success( function(res){
			if ( res.statusCode == 200 ) {
				$scope.success();
				$scope.db.find( 'role',{order:{'id':'ASC'}}).success(function(data){
					$scope.data = catRole(data);
				});	
			} else {
				$scope.error({info:res.message});
			}
		} );
	}
} )
.controller( 'UserAddCtrl' , function($scope){	
	$scope.db.find( 'role',{order:{'id':'ASC'}}).success(function(data){
		$scope.data = catRole(data);
	});	
	
	$scope.submit = function() {
		$scope.db.url = APP_PATH + '/Rbac/addUserHandler';
		$scope.db.httpPost('',$scope.user).success( function(res){
			if ( res.statusCode == 200 ) {
				$scope.success();
			} else {
				$scope.error({info:res.message});
			}
		} );
	}
} )
.controller( 'UserPasswordCtrl' , function($scope){	
	$scope.user = _USER;
	$scope.submit = function() {
		$scope.db.url = APP_PATH + '?c=User&a=newPassword';
		$scope.db.httpPost('',$scope.user).success( function(res){
			$scope.execute(res)
		} );
	}
} )
.controller( 'UserEditCtrl' , function($scope){	
	$scope.user = _USER;
	$scope.submit = function() {
		$scope.db.url = APP_PATH + '?c=User&a=newInfo';
		$scope.db.httpPost('',$scope.user).success( function(res){
			$scope.execute(res)
		} );
	}
} )

;